package com.yangzehan.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yangzehan.mall.common.utils.PageUtils;
import com.yangzehan.mall.common.utils.Query;
import com.yangzehan.mall.product.dao.CategoryDao;
import com.yangzehan.mall.product.entity.CategoryEntity;
import com.yangzehan.mall.product.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> groupselect() {
        List<CategoryEntity> entities = baseMapper.selectList(null);
        List<CategoryEntity> list;
        list = entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid()==0)
                .peek((menu)-> menu.setChildren(getPChildren(menu,entities)))
                .sorted((o1, o2) -> o1.getSort()==null?0:o1.getSort()-(o2.getSort()==null?0:o2.getSort()))
                .collect(Collectors.toList());

        return list;
    }

    @Override
    public void LogicremoveByIds(List<Long> asList) {
        //todo  删除前判断是否被其他地方引用
        baseMapper.deleteBatchIds(asList);
    }

    private List<CategoryEntity> getPChildren(CategoryEntity menu,List<CategoryEntity> entities) {



        return entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(menu.getCatId()))
                .peek(categoryEntity -> categoryEntity.setChildren(getPChildren(categoryEntity, entities)))
                .sorted((o1, o2) -> o1.getSort()==null?0:o1.getSort()-(o2.getSort()==null?0:o2.getSort()))
                .collect(Collectors.toList());
    }

}